Burst balloons

Time: O(N^3); Space: O(N^2); hard

Given n balloons, indexed from 0 to n-1. Each balloon is painted with a number on it represented by array nums. You are asked to burst all the balloons. If the you burst balloon i you will get nums[left] * nums[i] * nums[right] coins. Here left and right are adjacent indices of i. After the burst, the left and right then becomes adjacent.

Find the maximum coins you can collect by bursting the balloons wisely.

Notes:

  • You may imagine nums[-1] = nums[n] = 1. They are not real therefore you can not burst them.

  • 0 ≤ n ≤ 500, 0 ≤ nums[i] ≤ 100

Example 1:

Input: nums = [3,1,5,8]

Output: 167

Explanation:

  • nums = [3,1,5,8] –> [3,5,8] –> [3,8] –> [8] –> []

  • coins = 315 + 358 + 138 + 181 = 167

Example 2:

Input:nums = [4, 1, 5, 10]

Output:270

Explanation:

  • nums = [4, 1, 5, 10] burst 1, get coins 4 * 1 * 5 = 20

  • nums = [4, 5, 10] burst 5, get coins 4 * 5 * 10 = 200

  • nums = [4, 10] burst 4, get coins 1 * 4 * 10 = 40

  • nums = [10] burst 10, get coins 1 * 10 * 1 = 10

  • Total coins 20 + 200 + 40 + 10 = 270

Example 3:

Input:nums = [3,1,5]

Output:35

Explanation

  • nums = [3, 1, 5] burst 1, get coins 3 * 1 * 5 = 15

  • nums = [3, 5] burst 3, get coins 1 * 3 * 5 = 15

  • nums = [5] burst 5, get coins 1 * 5 * 1 = 5

  • Total coins 15 + 15 + 5 = 35

[2]:
class Solution1(object):
    """
    Time: O(N^3)
    Space: O(N^2)
    """
    def maxCoins(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        coins = [1] + [i for i in nums if i > 0] + [1]
        n = len(coins)
        max_coins = [[0 for _ in range(n)] for _ in range(n)]

        for k in range(2, n):
            for left in range(n - k):
                right = left + k
                for i in range(left + 1, right):
                    max_coins[left][right] = \
                        max(max_coins[left][right],
                            coins[left] * coins[i] * coins[right] +
                            max_coins[left][i] +
                            max_coins[i][right]
                           )

        return max_coins[0][-1]
[3]:
s = Solution1()

nums = [3,1,5,8]
assert s.maxCoins(nums) == 167

nums = [4, 1, 5, 10]
assert s.maxCoins(nums) == 270

nums = [3,1,5]
assert s.maxCoins(nums) == 35